﻿using System.Collections.ObjectModel;
using MyWindowsMediaPlayer.Libs.ViewModel;

namespace MyWindowsMediaPlayer.Libs.TreeView
{
	public class TreeViewItemViewModel : ViewModelBase
	{
		#region Members

		static readonly TreeViewItemViewModel DummyChild = new TreeViewItemViewModel();

		readonly ObservableCollection<TreeViewItemViewModel> _children;
		readonly TreeViewItemViewModel _parent;

		bool _IsExpanded;
		bool _IsSelected;

		#endregion

		#region Constructors
		protected TreeViewItemViewModel ( TreeViewItemViewModel parent, bool lazyLoadChildren )
		{
			this._parent = parent;
			this._children = new ObservableCollection<TreeViewItemViewModel>();

			if (lazyLoadChildren)
				this._children.Add(DummyChild);
			this._IsSelected = false;
		}

		private TreeViewItemViewModel ( )
		{
		}

		#endregion

		#region Presentation Members

		public ObservableCollection<TreeViewItemViewModel> Children
		{
			get { return this._children; }
		}

		public bool HasDummyChild
		{
			get { return this.Children.Count == 1 && this.Children[ 0 ] == DummyChild; }
		}

		public bool IsExpanded
		{
			get { return this._IsExpanded; }
			set
			{
				if (value != this._IsExpanded)
				{
					this._IsExpanded = value;
					this.OnPropertyChanged("IsExpanded");
				}

				// Expand all the way up to the root.
				if (this._IsExpanded && _parent != null)
					_parent.IsExpanded = true;

				// Lazy load the child items, if necessary.
				if (this.HasDummyChild)
				{
					this.Children.Remove(DummyChild);
					this.LoadChildren();
				}
			}
		}

		public bool IsSelected
		{
			get { return this._IsSelected; }
			set
			{
				if (value != this._IsSelected)
				{
					this._IsSelected = value;
					this.OnPropertyChanged("IsSelected");
				}
			}
		}

		protected virtual void LoadChildren ( )
		{
		}

		#endregion
	}
}
